package com.jxc.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.AgencyGrantRecord;
import com.jxc.model.po.Brand;
import com.jxc.model.po.DealerGrantRecord;
import com.jxc.model.po.Jhtj;
import com.jxc.model.po.Limit;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.RepertoryBrand;
import com.jxc.model.po.Resource;
import com.jxc.model.po.Role;
import com.jxc.model.po.RoleResource;
import com.jxc.model.po.User;
import com.jxc.model.po.Xstj;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.SessionInfo;
import com.jxc.model.vo.VBrand;
import com.jxc.model.vo.VDealerGrantRecord;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VRepertory;
import com.jxc.model.vo.VUser;
import com.jxc.service.BrandServiceI;
import com.jxc.service.RepertoryServiceI;
import com.jxc.service.UserServiceI;
import com.jxc.util.MD5;
import com.jxc.util.ResourceUtil;

@Service("userService")
public class UserServiceImpl implements UserServiceI {

	@Autowired
	private BaseDaoI<User> userDao;
	@Autowired
	private BaseDaoI<Limit> limitDao;
	@Autowired
	private BaseDaoI<AgencyGrantRecord> agencyDao;
	@Autowired
	private BaseDaoI<DealerGrantRecord> dealerDao;
	@Autowired
	private BaseDaoI<Repertory> repertoryDao;
	@Autowired
	private BaseDaoI<Brand> brandDao;
	@Autowired
	private BrandServiceI brandService;
	@Override
	public VUser get(Long id) {
		return this.changeModel(userDao.get(User.class, id));
	}

	@Override
	public List<VUser> combobox(VUser vuser) {
		List<VUser> vusers = new ArrayList<VUser>();
		try {
			vusers.addAll(this.changeModel(this.find(vuser, null)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vusers;
	}

	private List<VUser> changeModel(List<User> users) {
		List<VUser> vusers = new ArrayList<VUser>();
		if (users != null && users.size() > 0) {
			for (User user : users) {
				VUser vuser = new VUser();
				BeanUtils.copyProperties(user, vuser);
				if (user.getRole() != null) {
					Role role = user.getRole();
					vuser.setRoid(role.getId());
					vuser.setRoname(role.getName());
					if (user.getRepertory() != null) {
						Repertory repertory = user.getRepertory();
						vuser.setReid(repertory.getId());
						vuser.setRename(repertory.getName());
					}
				
				}if(user.getUserType()==1||user.getUserType()==5){
					String hql = "select lower_user_num,repertory_num from qxgl_limit where user_id="+user.getId();
					List<Object[]> li = userDao.findBySql(hql);
					for(Object[] ob:li){
						for (int i = 0; i < ob.length; i++) {
							vuser.setLowerUserNum(Long.parseLong(ob[i].toString()));
							vuser.setRepertoryNum(Long.parseLong(ob[++i].toString()));
						}
					}
				} 
				vusers.add(vuser);
			}
		}
		return vusers;
	}

	private VUser changeModel(User user) {
		if (user == null)
			return null;

		VUser vuser = new VUser();
		BeanUtils.copyProperties(user, vuser, new String[] { "password" });

		Role role = user.getRole();
		vuser.setRoid(role.getId());
		vuser.setRoname(role.getName());

		if (user.getRepertory() != null) {
			Repertory repertory = user.getRepertory();
			vuser.setReid(repertory.getId());
			vuser.setRename(repertory.getName());
		}
		if(user.getUser()!=null){
			User u = user.getUser();
			vuser.setUpid(u.getId());
		}

		return vuser;
	}

	private List<User> find(VUser vUser, VUser vuser) {
		//String hql = "from User t where t.isDeleted=false and t.username!='admin' ";

		//t.userType=6
		
		SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		
		String hql ="";
		//判断当前如果是登录的admin用户 
		if(sessionInfo.getLoginName().equals("admin")){
			
			hql= "from User t where t.isDeleted=false and t.username!='admin' and t.userType in (1,2,5) ";
			
		}else {
			
			hql= "from User t where t.isDeleted=false and t.username!='admin' ";
		}
		
		
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vUser, vuser, hql, values);

		if (vUser.getSort() != null && vUser.getOrder() != null) {
			hql += " order by " + vUser.getSort() + " " + vUser.getOrder();
		}
		return userDao.find(hql, values, vUser.getPage(), vUser.getRows());
	}

	/**
	 * 查询指定用户下面的子帐号
	 */
	@Override
	public List<VUser> selectUsers(VUser vUser){
		List<VUser> datas=new ArrayList<VUser>();
		if(vUser.getId()!=null){
			//sql
			String sql="select u.USER_NAME,q.name,u.REAL_NAME,u.MOBILE,u.CREATETIME,u.EXPIRYDATE,u.BIRTHDAY,u.ADRESS " +
					" from qxgl_user u join qxgl_role q " +
					" where u.ROLE_ID=q.id and u.USER_ID=" +vUser.getId()+
					" and u.ID<>u.USER_ID and u.ISDELETED=false " +
					" group by u.USER_NAME";
			//获取数据赋值
			List<Object[]> list=userDao.findBySql(sql);
			
			if(list!=null){
				
				for (Object[] objects : list) {
					VUser user=new VUser();
					
					//用户名
					user.setUsername(String.valueOf(objects[0]));
					//角色名
					user.setUusername(String.valueOf(objects[1]));
					//真实名称
					user.setRename(String.valueOf(objects[2]));
					//手机
					user.setMobile(String.valueOf(objects[3]));
					DateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
					try{
						//开始时间
					user.setCreateTime(format.parse(String.valueOf(objects[4])));
					}
					catch(Exception e){
							
					}
					
					try{
						user.setExpiryDate(format.parse(String.valueOf(objects[5])));
					}catch (Exception e) {
						// TODO: handle exception
					}
					
					try{
						user.setBirthday(format.parse(String.valueOf(objects[6])));
					}catch(Exception e){
						
					}
					//设置地址
					user.setAdress(String.valueOf(objects[7]));
					datas.add(user);
				}
				//for end
				
			}
			
			
		}
		
		return datas;
	}
	
	private Long total(VUser vUser, VUser vuser) {
		
	SessionInfo sessionInfo = (SessionInfo) ServletActionContext.getRequest().getSession().getAttribute(ResourceUtil.getSessionInfoName());
		
		String hql ="";
		//判断当前如果是登录的admin用户 
		if(sessionInfo.getLoginName().equals("admin")){
			
			hql= "select count(*) from User t where t.isDeleted=false and t.username!='admin' and t.userType in (1,2,5) ";
			return userDao.count(hql);
			
		}else {
			
			hql= "select count(*) from User t where t.isDeleted=false and t.username!='admin' ";
		}
		
		//String hql = "select count(*) from User t where t.isDeleted=false and t.username!='admin' ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vUser, vuser, hql, values);
		return userDao.count(hql, values);
	}

	private String addWhere(VUser vUser, VUser vuser, String hql,
			List<Object> values) {
		if (vUser.getUsername() != null
				&& !vUser.getUsername().trim().equals("")) {
			hql += " and t.username like ? ";
			values.add("%%" + vUser.getUsername().trim() + "%%");
		}

		if (vUser.getUserType() != null) {
			hql += " and t.userType = ? ";
			values.add(vUser.getUserType());
		}

		if (vUser.getRoid() != null) {
			hql += " and t.role.id = ? ";
			values.add(vUser.getRoid());
		}

		if (vUser.getReid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vUser.getReid());
		}
		if (vuser != null) {
				hql += " and t.user.id = ? ";
				values.add(vuser.getId());
			if(vuser.getId()!=null){
				hql += "and t.id != ?";
				values.add(vuser.getId());
			}
		}
		
		return hql;
	}

	@Override
	public Integer login(VUser user) {
		String hql1 = "from User u where u.isDeleted=false and u.username = ? and u.password = ? ";
		User dUser1 = userDao.get(hql1, new Object[] { user.getUsername().trim(),
				MD5.md5(user.getPassword())});
		if(dUser1!=null){
			String hql = "from User u where u.isDeleted=false and u.username = ? and u.password = ? and u.validDate <= ? ";
			User dUser = userDao.get(hql, new Object[] { user.getUsername().trim(),
					MD5.md5(user.getPassword()), new Date()});
			if (dUser != null) {
				String hql2 = "from User u where u.isDeleted=false and u.username = ? and u.password = ? and u.validDate <= ? and u.expiryDate > ?";
				User dUser2 = userDao.get(hql2, new Object[] { user.getUsername().trim(),
						MD5.md5(user.getPassword()), new Date(), new Date()});
				if(dUser2!=null){
					String hql3 = "from User u where u.isDeleted=false and u.username = ? and u.password = ? and u.validDate <= ? and u.expiryDate > ? and u.status = ?";
					User dUser3 = userDao.get(hql3, new Object[] { user.getUsername().trim(),
							MD5.md5(user.getPassword()), new Date(), new Date(), 1 });
					if(dUser3!=null){
						return 1;
					}else{
						return 30;//用户已失效
					}
				}else{
					return 20;//用户已过期,请联系管理员休整相关事宜
				}
				
			}else{
				return 10;//用户未到启用时间
			}
		}else{
			return 0;//用户名和密码不匹配的时候
		}
	}
	
	public VUser login1(VUser user) {
		String hql = "from User u where u.isDeleted=false and u.username = ? and u.password = ? and u.validDate <= ? and u.expiryDate > ? and u.status = ?";
		User dUser = userDao.get(hql, new Object[] { user.getUsername(),
				MD5.md5(user.getPassword()), new Date(), new Date(), 1 });
	
		VUser u = changeModel(dUser);
		if(u!=null){
		u.setPassword(user.getPassword());
		Map<Long, String> authIdsMap = new HashMap<Long, String>();
		String authIds = "";
		String authNames = "";
		Map<Long, String> authUrlsMap = new HashMap<Long, String>();
		String authUrls = "";
		List<RoleResource> roleResources = dUser.getRole()
				.getRoleResources();
		if (roleResources != null && roleResources.size() > 0) {
			for (RoleResource roleResource : roleResources) {
				Resource resource = roleResource.getResource();
				authIdsMap.put(resource.getId(), resource.getName());
				authUrlsMap.put(resource.getId(), resource.getUrl());
			}
		}
		boolean b2 = false;
		for (Long id : authIdsMap.keySet()) {
			if (b2) {
				authIds += ",";
				authNames += ",";
			}
			authIds += id;
			authNames += authIdsMap.get(id);
			b2 = true;
		}
		u.setAuthIds(authIds);
		u.setAuthNames(authNames);
		boolean b3 = false;
		for (Long id : authUrlsMap.keySet()) {
			if (b3) {
				authUrls += ",";
			}
			authUrls += authUrlsMap.get(id);
			b3 = true;
		}
		u.setAuthUrls(authUrls);
		}
		return u;
		
	}

	@Override
	public DataGrid datagrid(VUser vuser) {
		DataGrid j = new DataGrid();
		j.setRows(this.changeModel(this.find(vuser, null)));
		j.setTotal(this.total(vuser, null));
		return j;
	}

	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					User u = userDao.get(User.class, Long.valueOf(id.trim()));
					if (u != null) {
						u.setIsDeleted(true);
						userDao.update(u);
					}
				}
			}
		}

	}

	@Override
	public void editUserInfo(VUser vuser) {
		if (vuser.getPassword() != null
				&& !vuser.getPassword().trim().equals("")) {
			User t = userDao.get(User.class, vuser.getId());
			t.setPassword(MD5.md5(vuser.getPassword()));
		}

	}

	@Override
	public void save(VUser vuser) {
		User u = new User();
		vuser.setPassword("123456");
		BeanUtils.copyProperties(vuser, u, new String[] { "password" });
		if (vuser.getCreateTime() == null) {
			u.setCreateTime(new Date());
		}
		if (vuser.getRoid() != null) {
			Role role = new Role();
			role.setId(vuser.getRoid());
			u.setRole(role);
		}
		if (vuser.getReid() != null) {
			Repertory repertory = repertoryDao.get(Repertory.class, vuser.getReid());
			u.setRepertory(repertory);
			User user = repertory.getUser();
			u.setUser(user);
		}else{
			u.setUser(u);
			if(vuser.getLowerUserNum()!=null&&vuser.getRepertoryNum()!=null){
				Limit li = new Limit();
				li.setUser(u);
				li.setLowerUserNum(vuser.getLowerUserNum());
				li.setRepertoryNum(vuser.getRepertoryNum());
				limitDao.save(li);
			}
		}
		if(vuser.getValidDate()==null){
			u.setValidDate(new Date());
		}else{
			u.setValidDate(vuser.getValidDate());
		}
		u.setIsDeleted(false);
		u.setPassword(MD5.md5(vuser.getPassword()));
		userDao.save(u);
	}

	@Override
	public void update(VUser vuser) {
		User u = userDao.get(User.class, vuser.getId());
		BeanUtils.copyProperties(vuser, u, new String[] { "id", "password" });
		if (vuser.getCreateTime() == null) {
			u.setCreateTime(new Date());
		}
		if (vuser.getPassword() != null
				&& !vuser.getPassword().trim().equals("")) {
			u.setPassword(MD5.md5(vuser.getPassword()));
		}
		if (vuser.getRoid() != null) {
			Role role = new Role();
			role.setId(vuser.getRoid());
			u.setRole(role);
		}
		if (vuser.getReid() != null) {
			Repertory repertory = repertoryDao.get(Repertory.class, vuser.getReid());
			u.setRepertory(repertory);
			User user = repertory.getUser();
			u.setUser(user);
		}else{
			u.setUser(u);
			if(vuser.getLowerUserNum()!=null&&vuser.getRepertoryNum()!=null){
				Limit li = getLimitByUid(u.getId());  
				if(li!=null){
					li.setLowerUserNum(vuser.getLowerUserNum());
					li.setRepertoryNum(vuser.getRepertoryNum());
					limitDao.update(li);
				}else{
					Limit la = new Limit();
					la.setUser(u);
					la.setLowerUserNum(vuser.getLowerUserNum());
					la.setRepertoryNum(vuser.getRepertoryNum());
					limitDao.save(la);
				}
			}
		}
		u.setIsDeleted(false);
		userDao.update(u);  
	}

	public Limit getLimitByUid(Long uid){
		String hql = "select id from qxgl_limit where user_id="+uid;
		BigDecimal a = userDao.countSQL2(hql);
		if(a==null)a=new BigDecimal(0);
		Long id = a.longValue();
		Limit li = limitDao.get(Limit.class, id);
		return li;
	}
	@Override
	public List<VUser> agency(VUser vUser) {
		String hql = "select t from User t where t.userType=2 and t.isDeleted=false";
		List<Object> values = new ArrayList<Object>();
		values.add(vUser.getId());
		List<User> users = userDao.find(hql);
		List<User> exit = new ArrayList<User>();
		if (users != null && users.size() > 0) {
			for (User user : users) {
				String hql2 = "from AgencyGrantRecord t where t.agency.id=? and t.dealer.id=?";
				List<Object> values2 = new ArrayList<Object>();
				values2.add(user.getId());
				values2.add(vUser.getId());
				List<AgencyGrantRecord> agencys = agencyDao.find(hql2, values2,
						1, 1);
				if (agencys != null && agencys.size() > 0) {
					exit.add(user);
				}
			}
			users.removeAll(exit);
		}
		return changeModel(users);
	}

	@Override
	public void changePassword(VUser vUser) {
		User u = userDao.get(User.class, vUser.getId());
		if (vUser.getPassword() != null
				&& !vUser.getPassword().trim().equals("")) {
			u.setPassword(MD5.md5(vUser.getPassword()));
			userDao.update(u);
		}

	}
	
	@Override
	public void changePointTactics(VUser vUser) {
		User u = userDao.get(User.class, vUser.getId());
		if (vUser.getMoneyPointProp() != null) {
			u.setMoneyPointProp(vUser.getMoneyPointProp());
		}
		if (vUser.getPointMoneyProp() != null) {
			u.setPointMoneyProp(vUser.getPointMoneyProp());
		}
		if (vUser.getPointDeductionBase() != null) {
			u.setPointDeductionBase(vUser.getPointDeductionBase());
		}
		if(vUser.getPointMoneyProp() != null||vUser.getMoneyPointProp() != null||vUser.getPointDeductionBase() != null){
			userDao.update(u);
		}

	}

	@Override
	public List<VUser> combobox(VUser vUser, VUser vuser) {
		List<VUser> vusers = new ArrayList<VUser>();
		vusers.addAll(this.changeModel(this.find(vUser, vuser)));
		return vusers;
	}

	/* (non-Javadoc)
	 * @see com.jxc.service.UserServiceI#findAllDealer(com.jxc.model.vo.VUser)
	 */
	@Override
	public List<VUser> findAllMyDealer(VUser vUser) {
		List<VUser> vu = new ArrayList<VUser>();

		try {
			List<DealerGrantRecord> list = new ArrayList<DealerGrantRecord>();
			
			//查询用户
			String hql = "select t from DealerGrantRecord t where t.isDelete=false and t.agency.id="+vUser.getId();
			list = dealerDao.find(hql);
			for(DealerGrantRecord dgr : list){
				VUser vuser = new VUser();				
				User u = userDao.get(User.class, dgr.getDealer().getId());
				BeanUtils.copyProperties(u, vuser);
				vu.add(vuser);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vu;
	}
	
	/* (non-Javadoc)
	 * @see com.jxc.service.UserServiceI#findAllDealer(com.jxc.model.vo.VUser)
	 */
	@Override
	public List<VUser> findAllMyAgency(VUser vUser) {
		List<VUser> vu = new ArrayList<VUser>();

		try {
			List<DealerGrantRecord> list = new ArrayList<DealerGrantRecord>();
			
			//查询用户
			String hql = "select t from DealerGrantRecord t where t.isDelete=false and t.dealer.id="+vUser.getId();
			list = dealerDao.find(hql);
			for(DealerGrantRecord dgr : list){
				VUser vuser = new VUser();				
				User u = userDao.get(User.class, dgr.getAgency().getId());
				BeanUtils.copyProperties(u, vuser);
				vu.add(vuser);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vu;
	}
	
	@Override
	public DataGrid datagrid(VUser vUser, VUser vuser) {
		DataGrid j = new DataGrid();
		j.setRows(this.changeModel(this.find(vUser, vuser)));
		j.setTotal(this.total(vUser, vuser));
		return j;
	}

	@Override
	public DataGrid dealer(VUser vUser) {
		DataGrid j = new DataGrid();
		System.out.println(vUser.getBrandname());
		try {
			List<User> uu = new ArrayList<User>();
			List<VUser> vu = new ArrayList<VUser>();
//			String udid = findDgr(vUser.getId());
			User user = userDao.get(User.class, vUser.getId());
			List<Brand> brandList = user.getBrands();
			int flag = 0;//0:没有相关品牌 1：品牌搜索条件为空、存在相关品牌 2：品牌相关，且与搜索条件相符

			//查询用户
			String hql = "select t from Brand b join b.user t where t.isDeleted=false and t.userType in (1,5)";
			List<Object> values = new ArrayList<Object>();
			hql = addWhere(vUser, hql, values);
			
			uu = userDao.find(hql, values,vUser.getPage(),vUser.getRows());
			for(User u : uu){
				VUser vuser = new VUser();
				List<DealerGrantRecord> dgrlist =  findDealerGrantRecord(u.getId(), vUser.getId());
				if(dgrlist.size()>0){
					continue;
					//加入关联信息（由于需求变动，经销商查询不再显示已建立连接的经销商，所以这里如果存在，直接跳过）
//					DealerGrantRecord dgr = dgrlist.get(0);
//					BeanUtils.copyProperties(dgr, vuser);
				}
				vuser.setSameBrands("");
				flag = 0;
				List<Brand> brands = u.getBrands();
				for(Brand bd : brands){
					for(Brand ba : brandList){
						if(ba.getName().equals(bd.getName())){
							vuser.setSameBrands(vuser.getSameBrands()+bd.getName()+",");
							if(vUser.getBrandname()!=null&&!vUser.getBrandname().trim().equals("")){
								if(vUser.getBrandname().trim().equals(bd.getName().trim())){
									flag = 2;
								}
							}else{
								flag = 1;
							}						
						}
					}
				}
				if(vUser.getBrandname()!=null&&!vUser.getBrandname().trim().equals("")){
					if(flag!=2){
						continue;
					}
				}else if(flag==0){
					continue;
				}				
				BeanUtils.copyProperties(u, vuser);

				List<Brand>  vbs = u.getBrands();
				String brid = "";
				String brnm = "";
				for(Brand b:vbs){
					if(b.getIsDelete()!=true){
						brid += b.getId()+",";
						brnm += b.getName()+",";
					}
				}
				if(brid.length()>1){
					vuser.setBrandids(brid.substring(0, brid.length()-1));
					vuser.setBrandname(brnm.substring(0, brnm.length()-1));
				}
				vu.add(vuser);
			}
			j.setRows(vu);
			j.setTotal(new Long(vu.size()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return j;
	}
	
	/* (non-Javadoc)
	 * @see com.jxc.service.UserServiceI#myDealer(com.jxc.model.vo.VUser)
	 */
	@Override
	public DataGrid myDealer(VUser vUser) {
		DataGrid j = new DataGrid();

		try {
			List<VUser> vu = new ArrayList<VUser>();
			List<DealerGrantRecord> list = new ArrayList<DealerGrantRecord>();
			User user = userDao.get(User.class, vUser.getId());
			List<Brand> brandList = user.getBrands();
			
			//查询用户
			String hql = "select t from DealerGrantRecord t join t.dealer d where t.isDelete=false and t.agency.id="+vUser.getId();
			List<Object> values = new ArrayList<Object>();			
			hql = addWhereMyDealer(vUser,hql,values);
			list = dealerDao.find(hql, values,vUser.getPage(),vUser.getRows());
			int flag = 0;//0:没有相关品牌 1：品牌搜索条件为空、存在相关品牌 2：品牌相关，且与搜索条件相符
			for(DealerGrantRecord dgr : list){
				VUser vuser = new VUser();
				BeanUtils.copyProperties(dgr, vuser);
				
				User u = userDao.get(User.class, dgr.getDealer().getId());
				BeanUtils.copyProperties(u, vuser);
				
				flag = 0;
				vuser.setSameBrands("");
				List<Brand> brands = u.getBrands();
				for(Brand bd : brands){
					for(Brand ba : brandList){
						if(ba.getName().equals(bd.getName())){
							vuser.setSameBrands(vuser.getSameBrands()+bd.getName()+",");
							if(vUser.getBrandname()!=null&&!vUser.getBrandname().trim().equals("")){
								if(vUser.getBrandname().trim().equals(bd.getName().trim())){
									flag = 2;
								}
							}else{
								flag = 1;
							}			
						}
					}
				}
				if(vUser.getBrandname()!=null&&!vUser.getBrandname().trim().equals("")){
					if(flag!=2){
						continue;
					}
				}else if(flag==0){
					continue;
				}		
				String brid = "";
				String brnm = "";
				for(Brand b:brands){
					if(b.getIsDelete()!=true){
						brid += b.getId()+",";
						brnm += b.getName()+",";
					}
				}
				if(brid.length()>1){
					vuser.setBrandids(brid.substring(0, brid.length()-1));
					vuser.setBrandname(brnm.substring(0, brnm.length()-1));
				}
				vu.add(vuser);
			}
			
			j.setRows(vu);
			j.setTotal(new Long(vu.size()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 针对我的经销商的addwhere
	 * @param vUser
	 * @param hql
	 * @param values
	 * @return String
	 */
	public String addWhereMyDealer(VUser vUser, String hql, List<Object> values) {
		// TODO Auto-generated method stub
		if (vUser.getRealName()!=null&&!vUser.getRealName().equals("")) {
			hql += "and ( d.realName like ? ";
			values.add("%%"+vUser.getRealName().trim() + "%%");
			hql += "or d.username like ? )";
			values.add("%%"+vUser.getRealName().trim() + "%%");
		}
		if (vUser.getSort() != null && vUser.getOrder() != null) {
			hql += " order by t." + vUser.getSort() + " " + vUser.getOrder();
		}
		return hql;
	}

	private Long dealerTotal(VUser vUser, Object object) {
		String hql = "from User t where t.isDeleted=false and t.userType=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vUser,  hql, values);

		if (vUser.getSort() != null && vUser.getOrder() != null) {
			hql += " order by " + vUser.getSort() + " " + vUser.getOrder();
		}
		return userDao.count(hql,values);
	}


	public String findDgr(Long id) {
		List<DealerGrantRecord> list = new ArrayList<DealerGrantRecord>();
		String hql = "from DealerGrantRecord t where t.isDelete=false and t.agency.id="+id;
		list = userDao.findList(hql);
		String ids = "";
		if(list.size()>0){
			for(DealerGrantRecord  vd: list){
				ids += vd.getDealer().getId()+",";
			}
		}
		return  ids;
	}
	
	/**
	 * 根据建立关系的代理商和经销商id查询出对应的关系记录
	 * @param dealerId
	 * @param agencyId
	 * @return List<DealerGrantRecord>
	 */
	public List<DealerGrantRecord> findDealerGrantRecord(Long dealerId,Long agencyId) {
		List<DealerGrantRecord> list = new ArrayList<DealerGrantRecord>();
		String hql = "from DealerGrantRecord t where t.isDelete=false and t.dealer.id="+dealerId+" and t.agency.id="+agencyId;
		list = userDao.findList(hql);
		return list;
	}

	@Override
	public List<User> findDealer(VUser vUser) {
		String hql = "select t from Brand b join b.user t where t.isDeleted=false and t.userType in (1,5)";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vUser,  hql, values);

		if (vUser.getSort() != null && vUser.getOrder() != null) {
			hql += " order by " + vUser.getSort() + " " + vUser.getOrder();
		}
		return userDao.find(hql, values, vUser.getPage(), vUser.getRows());
	}	
	
	public List<Jhtj> findJhsum(Long id){
		List<Jhtj> list = new ArrayList<Jhtj>();
		String hql = "from Jhtj t where t.userid=11";//+id;
		list = userDao.findList(hql);
		return list;
	}
	
	/**
	 * 针对经销商查询（dealer）的addWhere
	 * @param vUser
	 * @param hql
	 * @param values
	 * @return String 
	 */
	private String addWhere(VUser vUser,  String hql,
			List<Object> values) {
		if (vUser.getBrandname() != null
				&& !vUser.getBrandname().trim().equals("")) {
			hql += " and b.name like ? ";
			values.add("%%"+vUser.getBrandname().trim() + "%%");
		}
		if (vUser.getRealName()!=null&&!vUser.getRealName().equals("")) {
			hql += "and ( t.realName like ? ";
			values.add("%%"+vUser.getRealName().trim() + "%%");
			hql += "or t.username like ? )";
			values.add("%%"+vUser.getRealName().trim() + "%%");
		}
		hql += " group by t ";
		if (vUser.getSort() != null && vUser.getOrder() != null) {
			hql += " order by t." + vUser.getSort() + " " + vUser.getOrder();
		}
		return hql;
	}

	@Override
	public List<Xstj> findSalesum(Long id) {
		List<Xstj> list = new ArrayList<Xstj>();
		String hql = "from Xstj t where t.userid="+id;
		list = userDao.findList(hql);
		System.out.println(list.size());
		return list;
	}

	@Override
	public Long findUsername(String username) {
		Long i = 0l;
		try {
			if(username!=null&&!username.trim().equals("")){
				String hql = " select count(*) from User t where t.isDeleted=0 and t.username = '"+username+"'";
				i = userDao.count(hql);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return i;
	}

	@Override
	public Long findLimitUser(Long userId) { 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Long i = null ;
		//包含自己在内的经销商或代理商有多少下级用户
		String hql = "select count(*) from qxgl_user where isdeleted=0 and status = 1 " +
				" and validdate <=date_format('"+sdf.format(new Date())+"','%Y%m%d') and " +
				" expirydate >date_format('"+sdf.format(new Date())+"','%Y%m%d') and user_id="+userId;
		BigInteger a = userDao.countSQL(hql);
		Long usl = a.longValue();
		//经销商或代理商被允许有多少下级用户
		String hql3 = "select lower_user_num from qxgl_limit where user_id="+userId;

		BigInteger c = userDao.countSQL(hql3);
		if(c!=null){
			Long nusl = c.longValue();
			if(usl<=nusl){
				i = 0l;
			}else {
				i = 1l;//1代表下级用户多了
			}
		}else{
			i = 0l;
		}
		
		return i;
		
	}

	@Override
	public Long findLimitRepertory(Long userId) {
		Long i = null ;
		//经销商或代理商有多少仓库
		String hql2 = "select count(*) from rkgl_repertory where IS_DELETE=0 and user_id="+userId;
		BigInteger b = userDao.countSQL(hql2);  
		Long rsl = b.longValue();
		//经销商或代理商被允许有多少仓库
		String hql4 = "select repertory_num from qxgl_limit where user_id="+userId;
		BigInteger d = userDao.countSQL(hql4);  
		if(d==null){
			
			return 0l;
			
		}
		Long nrsl = d.longValue();
		if(rsl+1l>nrsl){
			i = 1l ;//2代表仓库超出范围
		}else{
			i = 0l;//0代表对了
		} 
		return i;
	}

	@Override
	public VUser findUsernameById(Long uid) {
		VUser v = new VUser();
		String hql = " select user_name,real_name from qxgl_user where id="+uid;
		List<Object[]> list = userDao.findBySql(hql);
		for(Object[] o:list){
			for (int i = 0; i < o.length; i++) {
				v.setUsername(o[i].toString());
				v.setRealName(o[++i].toString());
			}
		}
		return v;
	}


}